using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace LastFMPPC
{
	class HttpClient
	{
		string host = string.Empty;
		string port = "";
		List<string> header = new List<string>();
		List<string> response = new List<string>();
		string status = "";

		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="host">Host name.</param>
		/// <param name="port">Port number.</param>
		public HttpClient(string host, string port)
		{
			this.host = host;
			this.port = port;
		}

		/// <summary>
		/// Gets the header list.
		/// </summary>
		public List<string> Header
		{
			get { return header; }
		}

		/// <summary>
		/// Gets the server response list.
		/// </summary>
		public List<string> Response
		{
			get { return response; }
		}

		/// <summary>
		/// Performs an Http request.
		/// </summary>
		/// <param name="url">The url.</param>
		public void Req(string url)
		{
			string line;
			string[] delimiters = new string[1];
			delimiters[0] = ": ";
			try
			{
				SocketConnection s = new SocketConnection(host, int.Parse(port));
				s.Connect();
				s.Send("GET http://" + host + ":" + port + url + " HTTP/1.1\r\n");
				s.Send("Host: " + host + "\r\n");
				s.Send("\r\n");

				status = s.ReadLine().Trim();
				if (status.IndexOf("OK") == -1)
				{
					throw new LastException("HttpClient.Req: Webrequest error!");
				}

				while (true)
				{
					line = s.ReadLine();
					if (line.Length == 0) break;
					header.Add(line);
				}
				while (true)
				{
					line = s.ReadLine();
					if (line.Length == 0) break;
					response.Add(line);
				}

				s.Close();
			}
			catch (LastException lexp)
			{
				throw lexp;
			}
			catch (Exception exp)
			{
				throw new LastException("HttpClient.Req: " + exp.Message);
			}
		}
	}
}
